<template>
  <div class="merak-container-has-aside">
    <div class="merak-aside">
      <treeNode  :defTreeValue="treeNodeDefaultOrgId"  @node-change="treeNodeChange"></treeNode>
    </div>
    <div v-waterMarker="{zIndex: 10}"  class="merak-card merak-table-wrapper merak-container-has-search" curPageName="66543f567ab">
      <!--到期合同为0不展示 -->
      <el-alert type="error" class="expiration-reminder" v-if="0" :closable="false">
        <div class="expiration-reminder-content">
          <el-icon :size="16" color="#E74C3D"><WarningFilled /></el-icon>
          <div>
            到期提醒: <span class="expiration-reminder-num">{{ expirationReminder }}人</span>合同即将到期
          </div>
          <div>点击查看</div>
        </div>
      </el-alert>

      <!-- 表格组件 -->
      <MerakXTable
        v-bind="tablePayload"
        :batch-click="handleBatchClick"
        :handler-click="handleHanderClick"
        :query-columns="queryColumns"
        :query-data="queryData"
        :show-header="false"
        style="margin-top: 28px"
      >
        <!-- 员工详情插槽 -->
        <template #employee_details="{ row }">
          <el-popover :show-arrow="false" width="auto" placement="right-start" popper-style="min-width: 472px">
            <template #reference>
              <el-button class="employee-button" link style="font-weight: bold">{{ row.employee_name }}</el-button>
            </template>
            <!-- 员工详情信息卡片 -->
            <!-- <InfoCard :data="row" /> -->
          </el-popover>
        </template>

        <template #signing_status_header_slot="{ column }">
          <div class="signing_status_header">
            {{ column.title }}
          </div>
        </template>
        <template #signing_status_slot="{ row }">
          <div class="signing_status">
            <div class="signing_status_item" @click="toRouter('/contract/signed','sign_contract', row)">
              <div class="signing_status_num">{{ row.signing_status.sign_contract }}</div>
              <!-- 人已签订 -->
              <div>{{($t('lang')=="ru"?"&nbsp;":'')}}{{$t('contract.profile_sign_contract_num')}}</div>
            </div>
            <div class="signing_status_item" @click="toRouter('/contract/noSigned','not_sign_contract', row)">
              <div class="signing_status_num">{{ row.signing_status.not_sign_contract }}</div>
              <!-- 人未签订 -->
              <div>{{($t('lang')=="ru"?"&nbsp;":'')}}{{$t('contract.profile_nosign_contract_num')}}</div>
            </div>
            <div class="signing_status_item" @click="toRouter('/contract/signed','expire_contract', row)">
              <div class="signing_status_num">{{ row.signing_status.expire_contract }}</div>
              <!-- 人合同即将到期 -->
              <div>{{($t('lang')=="ru"?"&nbsp;":'')}}{{$t('contract.profile_expire_contract')}}</div>
            </div>
          </div>
        </template>

        <template #handler="{ row }">
          <div style="display: flex">
            <!-- <el-button link type="danger" @click="renewal(row)">续签</el-button> -->
          </div>
        </template>
      </MerakXTable>
    </div>
  </div>
</template>
  
  <script setup lang="ts" name="contractProfile">
import router from "@/routers";
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElButton, ElPopover } from "element-plus";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import MerakXTable, { MerakXTableInstance, MerakXTableProps, MerakXTableColumn } from "@/components/MerakXTable";
import useLoading from "@/hooks/useLoading";
import { treeNodeDataInterFace } from "./index";
import { ResultEnum } from "@/enums/httpEnum";
import {
  Path,
  profileSignedGetTableColumns,
  profileSignedGetTableData,
  getRouterParams
} from "@/api/modules/personalManagementApi/contract";
import treeNode from "@/views/personalManagement/a-components/oragnizationTree/index.vue";

// treeNodeDefault 左侧组织架构默认选中项
const treeNodeDefaultOrgId = ref<number | string>(0);

//当前节点数据
const treeNodeData = ref<treeNodeDataInterFace>({
  level: 0,
  parent_id: 0,
  org_id: 0
});

//合同即将到期人数
const expirationReminder = ref<number>(0);

// 使用队列 loading 管理初始化页面加载状态
const { queueLoading, queueId } = useLoading();

// 获取路由参数 初始化 左侧树和 table 筛选参数
getRouterParams(router);

//设置url参数
const setUrlParams = () => {
  const newUrl = new URL(window.location.href);
  newUrl.searchParams.set("org_id", treeNodeDefaultOrgId.value);
  newUrl.searchParams.set("level", treeNodeData.value.level);
  newUrl.searchParams.set("parent_id", treeNodeData.value.parent_id);
  treeNodeDefaultOrgId.value = treeNodeData.value.org_id;
  window.history.pushState({}, "", newUrl.toString());
};
// 页面配置数据
const state = reactive<{
  filterOptions: Array<any>;
  statValue: string;
  statData: MerakStatDataType[][];
  statParams: Record<string, string>;
}>({
  // 高级搜索方案下拉选项
  filterOptions: [],
  // 统计筛选激活项
  statValue: "",
  // 统计筛选数据
  statData: [],
  // 统计筛选激活后筛选数据
  statParams: {}
});

// 动态计算表格的外部筛选数据
const params = computed(() => ({ ...state.statParams }));

// 表格配置属性
const tablePayload = reactive<MerakXTableProps>({
  // 列设置存储的数据对照值
  columnsByStore: [],
  // 表格行数据的唯一 key, 跟后端同步
  rowKey: "user_id",
  // 初始化的外部筛选数据
  params,
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  // ["multiple", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
  // columnType: ["handle"],
  // 批量操作选项
  batches: [{ type: "delete", text: "批量删除", color: "red" }]
  // 操作列选项
  // handles: [{ type: "delete", text: "删除", color: "red" }]
});

// 统计筛选激活触发 table 数据请求
const handleStatChange: MerakStatCardInstance["onChange"] = params => {
  state.statParams = params;
};

/**
 * 表格批量操作事件触发
 * @param type 同 tablePayload.batched 子项的 type
 * @param mode 表格选中的模式  current: 当前页  all: 所有页
 * @param selectedKeys 表格当前页选中模式下选中的行数据 key 的集合, 表格所有页选中模式下未选中的行数据 key 的集合
 */
const handleBatchClick: MerakXTableInstance["batchClick"] = async ({ type, mode, selectedKeys }) => {
  switch (type) {
    case "delete":
      return {
        // 是否刷新表格, 默认 false, 可选参数
        refresh: false,
        // 是否重置表格(分页、排序), 默认 false, 可选参数
        reset: false
      };
    default:
      return;
  }
};

/**
 * 表格操作列事件触发
 * @param type 同 tablePayload.handles 子项的 type
 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
 */
const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({ type, params }) => {
  switch (type) {
    case "delete":
      alert("delete");
      // 是否刷新表格, 默认 false, 可选参数
      return true;
    case "caht":
      alert("caht");
      // 是否刷新表格, 默认 false, 可选参数
      return true;
    default:
      return;
  }
};

// 获取高级搜索方案
const queryFilterOptions = async data => {
  // 初始化接口需要传入队列 loading 暴露的 id
};

// 获取统计数据
const queryStatData = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return getStatistics(queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      state.statData = Object.values(data).map(item => item);
      if (!!state.statData?.[0]?.[0]) {
        state.statData[0][0].horizontal = true;
      }
    }
  });
};

// 获取表头数据
const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return profileSignedGetTableColumns(Path.personnel, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      //获取表头后使用tableid 获取搜索方案
      queryFilterOptions(data);
      // 克隆表头数据作为列设置的对照数据
      tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data,
        columns: [...data.columns].map(column => {
          switch (column.field) {
            // 扩展插槽悬浮员工姓名展开员工详情卡片
            case "employee_name":
              column.slots = { default: "employee_details" };
              return column;
            case "signing_status": //扩展了，td 数据 插槽
              column.slots = { default: "signing_status_slot", header: "signing_status_header_slot" };
              return column;

            default:
              return column;
          }
        })
      };
    }
  });
};

/**
 * 获取表格数据
 * @param page 分页参数
 * @param sorts 多重排序参数
 * @param filters 表头筛选参数
 * @param from 外部由 tablePayload.params 传入的自定义参数
 */
const queryData: MerakXTableInstance["queryData"] = async ({ page, sorts, from }) => {
  // 创建请求表格数据的参数
  const params: Record<string, any> = {};
  // 如果有分页数据
  if (!!page) {
    Object.assign(params, { ...page });
  }
  // 如果有排序数据
  if (!!sorts) {
    for (let sort of sorts.values()) {
      console.log(sort);
    }
  }
  // 如果有自定义参数
  if (!!from) {
    for (let key of Object.keys(from)) {
      const item = from[key];
      !!item && (params[key] = item);
    }
  }
  Object.assign(params, { ...page, ...treeNodeData.value });

  // 初始化接口需要传入队列 loading 暴露的 id
  return profileSignedGetTableData(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      console.log(data);
      // expirationReminder.value = Number(data.dueContract)||0;
      return data.table_data;
    }
  });
};

// 初始化页面
const init = async () => {
  //获取路由参数，修改 treeNode 数据
  getRouterParams(router).then(res => {
    const { level, parent_id, org_id, job_nature } = res;
    treeNodeData.value.level =Number(level||0) ;
    treeNodeData.value.parent_id = Number(parent_id||0);
    treeNodeData.value.org_id = Number(org_id||0);
    treeNodeDefaultOrgId.value = Number(org_id||0);
    // paramsFromUrl.value.job_nature_id = job_nature_id;
  });
};

// 高级搜索表单
const ruleFormRef = ref<FormInstance>();
const searchform = ref({
  org_company: {
    label: "公司",
    value: "",
    type: "select",
    options: [
      { label: "北京企发", value: 1 },
      { label: "米格速达", value: 2 },
      { label: "新世纪农业", value: 3 }
    ]
  },
  org_department: {
    label: "部门",
    value: "",
    type: "select",
    options: [
      { label: "物流", value: 1 },
      { label: "研发", value: 2 },
      { label: "销售", value: 3 }
    ]
  },
  job_nature: {
    label: "工作性质",
    value: "",
    type: "select",
    options: [
      { label: "全职", value: 1 },
      { label: "兼职", value: 2 }
    ]
  },
  status: {
    label: "状态",
    value: "",
    type: "select",
    options: [
      { label: "在职", value: 1 },
      { label: "试用期", value: 2 }
    ]
  }
});

//跳转合同相关页面
const toRouter = (routerName, key,row) => { 
  let signing_status=row.signing_status;
  signing_status['job_nature']=signing_status.job_nature_id;

  if(row.signing_status[key]==0){//数据为0时不跳转
    return
  } 
  router.push({ path: routerName, query: {
     ...signing_status,
      ...treeNodeData.value
       ,...(key=='expire_contract'?{contract_end_soon:1}:{} )//如果是即将到期需要添加 contract_end_soon 搜索条件
      }
    });
};

//左侧组织架构
const treeNodeChange = (data: any) => {
  console.log(data)
  let {level=0,org_id=0,parent_id=0}=data;
  treeNodeData.value = { ...treeNodeData.value,...{level,org_id,parent_id}};
  treeNodeDefaultOrgId.value = treeNodeData.value.org_id;
  state.statParams = { up: new Date().getTime() };
  setUrlParams(); //点击组织架构，同步url参数，更新url
};

// 监听初始化队列 loading 状态
watch(queueLoading, () => {
  if (queueLoading.value) {
    // 页面初始化队列 loading 时不允许 table 自动 loading
    tablePayload.loading = false;
  } else if ("loading" in tablePayload) {
    // 队列 loading 完成后清除 table 受控的 loading 属性
    delete tablePayload.loading;
  }
});

// 运行初始化
onMounted(() => init());
</script>
  
  <style scoped lang="scss">
@import "./index.scss";
</style>
  